<?php
namespace Home\Controller;
use Think\Controller;

class ProductController extends PublicController {
	/**
	 * 产品列表，首先必须分类状态和产品状态都是可用的
	 */
	public function index() {

		$oop = D("ProductView");
		$mist_arr = array('product_name' => I("product_name"), 'product_label' => I("label"));
		$accute_arr = array('product_cat' => I("product_cat"));
		$cookie_arr = array();
		$con = searchCon($mist_arr, $accute_arr, $cookie_arr);
		$con['product_status'] = 1;
		$con['cat_status'] = 1;
		$data = pageInfo($oop, "product_sort desc", $con, 25);
		$this->assign("list", $data['list']);
		$this->assign("page", $data['show']);
		$this->display();
	}

	public function details() {
		$oop = D("ProductView");
		$con['product_status'] = 1;
		$con['cat_status'] = 1;
		$con['product_id'] = I("pid");
		$list = $oop->where($con)->find();
		if ($list) {
			$this->assign($list);
			$this->display();
		} else {
			$this->display("notfound");
		}
	}

	public function shopcart() {
		cookie("order_id", null);
		$this->display();
	}

	public function update($pid, $quantity) {
		$result = $this->beforeAddCart($pid, $quantity);
		if ($result) {
			$arr = array(
				"pid" => $pid,
				"quantity" => (int) $quantity,
				"price" => $result['product_price'],
				"dir" => $result['product_dir'],
				"img" => $result['product_img'],
				"product_name" => $result['product_name'],
				"product_desc" => $result['product_desc'],
				"product_cat" => $result['cat_name'],
			);
			$item = new \Cart\CartItem($arr);
			$this->cart->add($item);

			$cart_arr['cart_arr'] = $this->cart->toArray();
			$cart_arr['cart_items'] = $this->cart->totalItems();
			$cart_arr['cart_amount'] = $this->cart->total();

			$data['status'] = 1;
			$data['info'] = "Added successfully";
			$data['data'] = $cart_arr;

			$this->cart->save();
		} else {
			$data['status'] = 0;
			$data['info'] = "Product not found or out of stocks";
		}
		$this->ajaxReturn($data);
	}

	public function add() {
		$item = $this->cart->get(I("itemid"));
		$num = $item->quantity + 1;
		$item->set("quantity", $num);
		$this->cart->save();
		$this->redirect('shopcart');
	}

	public function minus() {
		$item = $this->cart->get(I("itemid"));
		$num = $item->quantity - 1;
		if ($num > 0) {
			$item->set("quantity", $item->quantity - 1);
		} else {
			$this->cart->remove(I("itemid"));
		}
		$this->cart->save();
		$this->redirect('shopcart');
	}
	/**
	 *删除产品
	 */
	public function remove() {
		$this->cart->remove(I("itemid"));
		$this->cart->save();
		$this->redirect("shopcart");
	}
	/**
	 * 清空购物车
	 */
	public function clear() {
		$this->cart->clear();
		$this->redirect("shopcart");
	}

}